﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ModeloGaleriaNET;
using System.Data.Objects;

namespace CADs
{
    public class AuditoriaCAD: BaseCAD
    {
        private int queryCount;
        private List<AuditoriaFilter> filtros;

        public AuditoriaCAD()
            : base()
        {
            filtros = new List<AuditoriaFilter>();
        }

        public bool InsertAuditoria(DateTime fecha, string descripcion, int tipo, int zona, int usuario, string ip)
        {
            try
            {
                if (usuario != -1)
                {
                    contexto.ExecuteStoreCommand("insert into auditorias (fecha, descripcion, tipo, zonaHoraria, usuario, ip) values ('" +
                        String.Format("{0:yyyy-MM-dd HH:mm:ss}", fecha) + "', '" + descripcion + "', " + tipo +
                        ", " + zona + ", " + usuario + ", '" + ip + "');");
                }
                else
                {
                    contexto.ExecuteStoreCommand("insert into auditorias (fecha, descripcion, tipo, zonaHoraria, ip) values ('" +
                        String.Format("{0:yyyy-MM-dd HH:mm:ss}", fecha) + "', '" + descripcion + "', " + tipo +
                        ", " + zona + ", '" + ip + "');");
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void SetQueryFilters(List<AuditoriaFilter> filters)
        {
            if (filters == null || filters.Count == 0)
            {
                filtros.Clear();
                this.filtros = new List<AuditoriaFilter>();
            }
            else
                this.filtros = filters;
        }

        public List<Auditoria> GetAuditoriaPaginated(int pagenum = 0)
        {
            int pagesize = int.Parse(Properties.Resources.PageSize);

            ObjectQuery<Auditoria> query = contexto.Auditorias;
            query.MergeOption = MergeOption.OverwriteChanges;

            foreach (var filtro in filtros)
                query = query.Where(filtro.Condition, filtro.Parameters.ToArray());

            queryCount = query.Count();

            return query.OrderByDescending(it => it.Id).Skip(pagenum * pagesize).Take(pagesize).ToList();
            /*return query.Skip("it.Id", "@Skip", new ObjectParameter("Skip", pagenum * pagesize))
                        .Top("@Limit", new ObjectParameter("Limit", pagesize))
                        .OrderByDescending(it => it.Id)
                        .ToList();*/
        }

        public int GetAuditoriaCount()
        {
            return queryCount;
        }
    }
}
